package com.yxuan.springboot.controller;

import com.github.pagehelper.PageInfo;
import com.yxuan.springboot.model.Feedback;
import com.yxuan.springboot.service.FeedBackService;
import com.yxuan.springboot.util.TencentCOSUploadFileUtil;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

import static com.yxuan.springboot.controller.BaseController.FAILCODE;

/**
 *
 * @author oldfish
 *   用户反馈功能
 * @date 2023-05-14 19:30:23
 */
@Controller
@RequestMapping("/feedbacks")
public class FeedbackController {

    @Autowired
    private FeedBackService feedBackService;

    @ApiOperation(value = "查询所有", notes = "查询所有反馈")
    @ResponseBody
    @GetMapping("/getall")
    public HashMap<String,Object> getAll() {
        try {
            HashMap<String, Object> result = new HashMap<>();
            List<Feedback> all = feedBackService.findAll();
            result.put("all",all);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            HashMap<String, Object> error = new HashMap<>();
            error.put("查询失败",FAILCODE);
            return error;
        }
    }

    @ApiOperation(value = "新建反馈", notes = "新建反馈")
    @PostMapping("/save")
    @ResponseBody
    public HashMap<String,Object> save(@RequestBody Feedback feedback) {
        try {
            HashMap<String,Object> result = new HashMap<>();
            feedback.setStatc("0");
            String save = feedBackService.save(feedback);
            result.put("success",feedback);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            HashMap<String, Object> error = new HashMap<>();
            error.put("查询失败",FAILCODE);
            return error;
        }
    }


    @ApiOperation(value = "更新状态", notes = "更新反馈状态")
    @PutMapping("/upd")
    @ResponseBody
    public HashMap<String, Object> update(@RequestBody Feedback feedback) {
        try {
            HashMap<String,Object> result = new HashMap<>();
            String upd = feedBackService.upd(feedback);
            result.put("success",upd);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            HashMap<String, Object> error = new HashMap<>();
            error.put("查询失败",FAILCODE);
            return error;
        }
    }


    @ApiOperation(value = "删除反馈", notes = "删除反馈")
    @DeleteMapping("/delete/{id}")
    @ResponseBody
    public HashMap<String, Object> delete(@PathVariable Integer id) {
        Feedback feedback = new Feedback();
        feedback.setId(id);
        try {
            HashMap<String,Object> result = new HashMap<>();
            String delete = feedBackService.remove(feedback);
            result.put("success",feedback);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            HashMap<String, Object> error = new HashMap<>();
            error.put("删除失败",FAILCODE);
            return error;
        }
    }

    @ApiOperation(value = "查询反馈", notes = "根据id查询")
    @GetMapping("/get/{id}")
    @ResponseBody
    public HashMap<String, Object> getById(@PathVariable String  id) {
        try {
            HashMap<String,Object> result = new HashMap<>();
            Feedback get = feedBackService.findTById(id);
            result.put("success",get);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            HashMap<String, Object> error = new HashMap<>();
            error.put("删除失败",FAILCODE);
            return error;
        }
    }

    /**
     * 分页
     */
    @ApiOperation(value = "反馈分页", notes = "反馈分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "起始页码", defaultValue = "1", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "limit", value = "每页记录条数", defaultValue = "10", required = true, dataType = "int", paramType = "query")
    })
    @GetMapping("/getpage")
    @ResponseBody
    public HashMap<String, Object> getPage(Integer page, Integer limit, Feedback feedback) {
        try {
            HashMap<String,Object> result = new HashMap<>();
            PageInfo<Feedback> getpage = feedBackService.findPageByPramas(page, limit, feedback);
            result.put("success",getpage);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            HashMap<String, Object> error = new HashMap<>();
            error.put("操作失败",FAILCODE);
            return error;
        }
    }



    @ApiOperation(value = "上传图片", notes = "上传反馈图片")
    @PostMapping("upload")
    @ResponseBody
    public String upload(@RequestParam("file") MultipartFile file) {
        if (null == file) {
            return "文件为空";
        }
        System.out.println(file);
        System.out.println(file.getSize());
        try {
            //1.获取源文件的输入流
            InputStream is = file.getInputStream();
            //2.获取源文件类型，文件后缀名
            String originalFileName = file.getOriginalFilename();
            //3.定义上传后的目标文件名(为了避免文件名称重复，此时使用UUID)
//            String newFileName = UUID.randomUUID().toString()+"."+originalFileName;
            String newFileName = UUID.randomUUID().toString()+"."+originalFileName;
            //4.通过上传路径得到上传的文件夹
            File fileLoad = new File("/root/upload/images");
            //4.1.若目标文件夹不存在，则创建
            if(!fileLoad.exists()){ //判断目标文件夹是否存在
                fileLoad.mkdirs();//4.2.不存在，则创建文件夹
            }
            //5.根据目标文件夹和目标文件名新建目标文件（上传后的文件）
            File newFile = new File("images",newFileName);  //空的目标文件
            //6.根据目标文件的新建其输出流对象
            FileOutputStream os = new FileOutputStream(newFile);
            //7.完成输入流到输出流的复制
            IOUtils.copy(is,os);
            //8.关闭流(先开后关)
            os.close();
            is.close();

            try {
                String baseUrl = "https://xc1.haoxnet.com:8098/images/";
                String fileUrl = newFileName;
                return "上传成功，访问地址为:" + baseUrl+fileUrl;
            } catch (Exception e) {
                e.printStackTrace();
                return BaseController.ERROR;
            }

        } catch (IOException e) {
            e.printStackTrace();
            return BaseController.ERROR;
        }
    }
}
